package osb.map.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import osb.map.main.Comment;
import osb.map.main.Login_Accessed;
import osb.map.main.Login_Main;
import osb.map.main.Main_Activity;
import osb.map.main.RegisterActivity;
import osb.map.map.Map;
import osb.map.publicdata.Public_Operate_And_Data;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ClientSocket implements Runnable
{
	
	public static ClientSocket Public_Static_ClientSocket;
	private Socket socket;
	private ObjectInputStream objIn; 
	private ObjectOutputStream objOut;
	private static DataPackage dataPackage_comment;
	private static DataPackage dataPackage_gps;
	
	static boolean IsLastComent=true;
	
	private static final int PORT = 8877;   //端口
	private String severIP;                 //IP地址
	boolean flag = false;                   //连接成功标志

	/**
	 * 连接服务器
	 */
	public void ConnectServer() 
	{
		Public_Static_ClientSocket = this;  
		try
		{
			java.security.Security.setProperty("networkaddress.cache.ttl", "0");
			InetAddress myServer = InetAddress.getByName("w747022951.eicp.net");
			String Address = myServer.getHostAddress();
			severIP=Address;
			severIP = "61.146.153.230";   // 测试地址 本地局域网  61.146.153.230
//			severIP = "192.168.1.116";   // 测试地址 本地局域网  61.146.153.230
			Log.v("服务器连接成功" + severIP, "网络连接");
		} catch (Exception e)
		{
			Log.v("服务器连接失败", "网络连接错误");
			return;
		}
	}
	
	/**
	 * 构建socket
	 */
	public void BuildClientSocket() 
	{
		try
		{
			socket = new Socket(severIP, PORT);
			objIn = new ObjectInputStream(socket.getInputStream());
			objOut = new ObjectOutputStream(socket.getOutputStream());
			Public_Operate_And_Data.IsConnectSuccess = true;          // 公共数据类中标志连接成功
			flag = true;                                              // socket连接成功

		} catch (Exception e)
		{
			Log.v("构建socket失败", "网络连接错误");
			return;
		}
	}
	
	/**
	 * 关闭连接
	 */
	public void exitServer() // 中断连接
	{
		try
		{
			DataPackage data = new DataPackage(msgType.Exit);
			objOut.writeObject(data);
			// 关闭socket
			objOut.close();
			objIn.close();
			socket.close();
		} catch (Exception e)
		{
			Log.v("中断连接失败", "网络连接错误");
		}
		flag = false;
		socket = null;
		objOut = null;
		objIn = null;
	}
	
	/**
	 * 数据包发送
	 * @param data
	 */
	public void sendMsg(DataPackage data)
	{
		// 网络未连接
		if (flag == false) 
		{
			Log.v("发送数据包出错，错误：网络连接失败","网络错误");
			return;
		}
		try
		{
			Log.v("发送-数据:"+data.toString()+"   时间:"+Public_Operate_And_Data.GetCurrentTimer(),"数据发送");
			System.out.println("发送-数据:"+data.toString()+"   时间:"+Public_Operate_And_Data.GetCurrentTimer()+'\n'); //输出消息。调试判断
			objOut.writeObject(data);
		} catch (Exception e)
		{
			Log.v("发送数据包出错，错误：数据包发送失败","网络错误");
			System.out.println("发送数据包出错，错误：数据包发送失败----网络错误  ++++  用户客户端"+'\n'); //输出消息。调试判断
		}
	}
	
	/**
	 * 客户端线程
	 * thread=new Thread(new ClientSocket()); //服务器
	 * thread.start(); 
	 */
	public void run()
	{
		boolean IsPostBack = true;     // 是否是第一次连接
		int Connect_error_count = 0;   // 连接失败次数 
		while (!flag) 
		{
			ConnectServer();      // 连接服务器
			BuildClientSocket();  // 构建自身socket
			 // 连接失败
			if (!flag)
			{
				Connect_error_count++;
				// 第一次连接而且 登陆失败
				if (IsPostBack)  
				{
					Log.v("第一次连接而且连接失败", "网络连接错误");
					IsPostBack = false;
				}
				Log.v("第" + Connect_error_count + "次尝试连接失败", "网络连接错误");
			}
		}
		// 监听接收服务器数据
		while (true)
		{
			try
			{
				// 读取服务器发送来的数据信息
				DataPackage data = (DataPackage) objIn.readObject(); 
				Log.v("接收-数据:"+data.toString()+"   时间:"+Public_Operate_And_Data.GetCurrentTimer(),"数据接收");
				System.out.println("接收-数据:"+data.toString()+"   时间:"+Public_Operate_And_Data.GetCurrentTimer()+'\n'); 
				
				
				//登陆
				if (data.type == msgType.Login_User_Success)        //登陆成功
				{
				} 
				else if (data.type == msgType.Login_User_PwdWrong)  //登陆失败
				{
					mHandler.sendEmptyMessage(0);                   //发送登陆失败消息
				}
				else if (data.type == msgType.Login_USer)           //登陆成功后将用户资料加载存储
				{
					Public_Operate_And_Data.User_id=data.dataUser.getUserId();  
					Public_Operate_And_Data.User_name=data.dataUser.getUserName();
					Public_Operate_And_Data.User_accout=data.dataUser.getUserAccount();		
					Public_Operate_And_Data.Islogin=true;                //标志用户已经登陆成功
					Login_Main.Public_Static_LoginMain.loginSuccess();   //执行登陆成功页面跳转加载		
				}
				//修改密码
				else if (data.type == msgType.ModPwd_User_Success)    //修改密码成功
				{
					Public_Operate_And_Data.user_pwd= Public_Operate_And_Data.user_pwd_willchange;  //真实密码赋值
					mHandler.sendEmptyMessage(1);                     //发送修改密码成功
					Log.v("修改密码成功", "网络连接");
				}
				else if (data.type == msgType.ModPwd_User_Wrong)      //修改密码失败
				{
				    mHandler.sendEmptyMessage(2);                     //发送修改密码失败
					Log.v("修改密码失败", "网络连接");
				}
				//注册
				else if (data.type == msgType.Register_User_Success)  //注册成功
				{
					 mHandler.sendEmptyMessage(3);                    //发送注册成功
					Log.v("注册成功", "网络连接");
				}
				else if (data.type == msgType.Register_User_Wrong)    //注册失败
				{
					 mHandler.sendEmptyMessage(4);                    //发送注册失败
					Log.v("注册失败", "网络连接");
				}
				//评论
				else if(data.type==msgType.Comment_Server_Reflash)    //接收
				{
					if(Public_Operate_And_Data.IsFirsttimeGetComment) //第一次获取评论
					{
						Public_Operate_And_Data.Vector_comment.add(data);
						if(IsLastComent)
						{
							Public_Operate_And_Data.lastcomment_id=data.dataComment.getUserId();       //最后一条评论的时间
							Public_Operate_And_Data.lastcomment_time=data.dataComment.getSendtime();   //最后一条评论的时间
							IsLastComent=false;
						}
					
					}
					else {
						dataPackage_comment=data;
						Public_Operate_And_Data.lastcomment_id=data.dataComment.getUserId();       //最后一条评论的时间
						Public_Operate_And_Data.lastcomment_time=data.dataComment.getSendtime();   //最后一条评论的时间
						IsLastComent=false;
						mHandler.sendEmptyMessage(5);   //刷新评论
					}
					
				}
				//获取小绿位置
				else if(data.type==msgType.DataGPS)
				{
					dataPackage_gps=data;
					mHandler.sendEmptyMessage(6);   // 获取小绿位置
				}
				else if(data.type==msgType.Pay_User_Success)
				{
					mHandler.sendEmptyMessage(7);   // 付费成功
				}
				else if(data.type==msgType.Pay_User_Wrong)
				{
					mHandler.sendEmptyMessage(8);   // 付费失败
				}
			}
			// 服务器连接中断
			catch (IOException e)
			{
//				mHandler.sendEmptyMessage(9);	
//				exitServer();
//				return;
			} 
			catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}
		}
	}

	Handler mHandler = new Handler()
	{
		
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case 0:     //登陆失败
				Login_Main.Public_Static_LoginMain.loginUserPwdWrong();
				break;
			case 1:     //修改密码成功
				Login_Accessed.Public_Static_Login_Accessed.ModpwdSuccess();
				break;
			case 2:     //修改密码失败
				Login_Accessed.Public_Static_Login_Accessed.ModpwdWrong();
				break;
			case 3:     //注册成功
				RegisterActivity.public_Static_RegisterActivity.registerSuccess();
				break;
			case 4:     //注册失败
				RegisterActivity.public_Static_RegisterActivity.registerWrong();
				break;
			case 5:     //刷新评论
				Comment.public_Static_cCommentActivity.Refresh(dataPackage_comment);
				break;
			case 6:     //获取小绿位置
				Map.Public_Static_Map.busLocalAskSuccess(dataPackage_gps.dataGPS);
				break;
			case 7:      //支付成功
				Main_Activity.Public_Static_OSBActivity.paysuccess();
				break;
			case 8:     //支付失败
				Main_Activity.Public_Static_OSBActivity.payfalse();
				break;
			case 9:     //服务器连接中断
				break;
			default:
//				Public_Operate_And_Data.IsConnectSuccess = false;
				break;
			}
			super.handleMessage(msg);
		}
	};
}
